/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.executor;

import cn.easyplatform.contexts.Contexts;
import cn.easyplatform.entities.BaseEntity;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.log.LogManager;
import cn.easyplatform.messages.vos.executor.ErrorVo;
import cn.easyplatform.spi.listener.event.MessageEvent;
import cn.easyplatform.type.DeviceType;
import cn.easyplatform.util.MessageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public abstract class AbstractExecutor<T extends BaseEntity> implements
        IExecutor<T> {

    protected final static Logger log = LoggerFactory.getLogger(AbstractExecutor.class);

    protected CommandContext cc;

    protected T task;

    private Object[] args;

    @Override
    public Object exec(CommandContext cc, T task, Object... args) {
        this.cc = cc;
        this.task = task;
        this.args = args;
        if (cc.getUser().getDeviceType() == DeviceType.AJAX)
            cc.getEngineConfiguration().getKernelThreadPoolExecutor()
                    .execute(this);
        else
            return perform(args);
        return null;
    }

    @Override
    public void run() {
        Contexts.set(CommandContext.class, cc);
        LogManager.beginRequest(cc.getEnv().getId(), cc.getUser());
        try {
            perform(args);
        } catch (Exception ex) {
            if (log.isErrorEnabled())
                log.error("perform", ex);
            cc.send(new MessageEvent(getId(), new ErrorVo(MessageUtils.getMessage(ex))));
        } finally {
            Contexts.clear();
        }
    }

    protected abstract String getId();

    protected abstract Object perform(Object... args);
}
